package com.example.demo.controller;

import com.example.demo.common.dto.CommonResult;
import com.example.demo.common.dto.Page;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import com.example.demo.vo.UserParam;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    UserMapper userMapper;

    /**
     * 发分页查询
     *
     * @return 列表
     */
    @PostMapping("/page")
    public CommonResult<Page<User>> findByPage(@RequestBody UserParam userParam) {

        Integer pageNo = userParam.getPageNo();
        Integer pageSize = userParam.getPageSize();
        String name = userParam.getName();

        Integer offset = (pageNo - 1) * pageSize;
        List<User> userData = userMapper.findByPage(offset, pageSize, name);
        Page<User> page = new Page<>();
        page.setData(userData);
        Integer total = userMapper.countUser();
        page.setTotal(total);
        page.setPageNo(pageNo);
        page.setPageSize(pageSize);
        return CommonResult.success(page);
    }

    /**
     * 详情
     *
     * @param id 主键
     * @return 详情
     */
    @GetMapping("getDetail/{id}")
    public CommonResult<User> getDetail(@PathVariable("id") Long id) {
        User detail = userMapper.getDetail(id);
        return CommonResult.success(detail);
    }


    /**
     * 插入数据
     *
     * @param user 用户
     * @return 结果
     */
    @PostMapping("add")
    public CommonResult<?> addUser(@RequestBody User user) {
        userMapper.save(user);
        return CommonResult.success(user);
    }

    /**
     * 更新数据
     *
     * @param user 用户消息
     * @return 结果
     */
    @PostMapping("updateById")
    public CommonResult<?> updateUser(@RequestBody User user) {
        userMapper.updateById(user);
        return CommonResult.success(user);
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 结果
     */
    @GetMapping("deleteById")
    public CommonResult<?> deleteById(Long id) {
        userMapper.deleteById(id);
        return CommonResult.success();
    }
}
